package com.ctbri.manage.file.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import static com.ctbri.manage.file.model.Constants.GRAPHQL_DIR;


/**
 * ClassName:GraphQLUtil
 * Package:com.ctbri.manage.file.util
 * Description:关于graphQL的工具类
 *
 * @Author:qs
 * @Create:2023/8/10
 * @Version：1.0
 */
public class GraphQLUtil {
    static final Logger logger = LoggerFactory.getLogger(GraphQLUtil.class);

    /**
     * 根据请求地址，文件名，调用DataHub接口
     *
     * @param serverUrl 请求地址
     * @param fileName  文件名
     * @return String 响应内容
     */
    public String getGraphSQLResponse(String serverUrl, String fileName) {
        String text = "";
        //1-读取graphQL文件
        String query = "*";
        FileUtil fileUtil = new FileUtil();
        String graphQL = fileUtil.getFileContent(GRAPHQL_DIR, fileName);

        //2-对graphQL内容，进行格式整理
        graphQL = graphQL.replaceAll("\"", "\\\\\"");
        graphQL = graphQL.replaceAll("\n", "\\\\r\\\\n");
        graphQL = graphQL.replaceAll("\\$\\{query\\}", query);
        graphQL = "{\"query\":\"" + graphQL + "\", \"variables\":{}}";

        //3-使用http协议调用datahub服务端接口
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");

        logger.info("请求Graph参数———————>" + graphQL);
        HttpClientUtil httpClientUtil = new HttpClientUtil();
        try {
            text = httpClientUtil.doPostJson(serverUrl, graphQL, headers);
            logger.info("Graph响应结果———————>" + text);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return text;
    }

}
